# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from models import NewUser, Article, ArticleType, Author, Poll, Comment, Keep
from .forms import LoginForm, RegisterForm, CommentForm
from islogin import islogin
import time
import os

from django.shortcuts import render, redirect
# login_required: 内置的一个装饰器，用来让用户强制登录。但是该装饰器必须配合值内置的登录函数login才能使用。
# 如果是自定义的登录注销逻辑，需要自己设置装饰器，实现强制用户登录的功能。
# from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.http import HttpResponseRedirect


# Create your views here.

def index(request):
    login_form = LoginForm()
    username = request.session.get('uname',False)
    # 查询所有的文章，展示在首页
    article_list = Article.objects.all()
    if username:
        return render(request, 'index.html', {'article_list': article_list, 'login_form': login_form, 'user': username})
    else:
        return render(request, 'index.html', {'article_list': article_list, 'login_form': login_form, 'user': False})


@islogin
def article(request, article_id):
    article = Article.objects.get(id=article_id)
    login_form = LoginForm()
    comment_form = CommentForm()
    # 文章所有的评论内容
    comments = article.comment_set.all()
    context = {
        'article': article,
        'login_form': login_form,
        'comment_form': comment_form,
        'comments': comments,
    }
    return render(request, 'article_page.html', context)


@islogin
def comment(request, article_id):
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
        content = comment_form.cleaned_data['comment']
        username = request.session.get('uname')
        user = NewUser.objects.get(uname=username)
        article = Article.objects.get(id=article_id)
        comment = Comment()
        comment.user = user
        comment.article = article
        # comment.user_id = user.id
        # comment.article_id = article_id
        comment.content = content
        comment.save()

        # 文章的总评论数+1
        article.acomment_num += 1
        article.save()
        return redirect('/blog/detail/'+str(article_id))
    else:
        return render(request, 'article_page.html')


@islogin
def keep(request, article_id):
    # 文章的收藏数+1
    article = Article.objects.get(id=article_id)
    username = request.session.get('uname')
    user = NewUser.objects.get(uname=username)
    # +1之前，判断是否已经收藏
    keep_obj = Keep.objects.filter(user_id=user.id, article_id=article_id)

    if keep_obj:
        # 不需要收藏
        return redirect('/blog/detail/'+str(article_id))
    else:
        keep = Keep()
        keep.user_id = user.id
        keep.article_id = article_id
        keep.save()
        article.akeep_num += 1
        article.save()
        return redirect('/blog/detail/' + str(article_id))




def mylogin(request):
    if request.method == 'GET':
        login_form = LoginForm()
        return render(request, 'login.html', {'login_form': login_form})
    else:
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = NewUser.objects.filter(uname=username, upwd=password)
            if user:
                # 用户名和密码都正确，登录成功，跳转至首页
                # 1.存入session，django自动返回一个cookie(sessionid)；
                # 2.将用户名存入cookie，以后每次访问这个网站的时候，先去读取一下cookie；
                request.session['uname'] = username

                url = request.COOKIES.get('url', '')
                if url == '':
                    # 直接在index首页进行登录的。
                    return redirect('/blog/index/')
                else:
                    # 说明是从某一个详情页面跳转进来的。
                    #
                    response = HttpResponseRedirect(url)
                    response.set_cookie('url', '')
                    return response
            else:
                return render(request, 'login.html', {'error_msg': '用户名或密码错误', 'login_form': login_form})
        else:
            return render(request, 'login.html', {'error_msg': '数据无效', 'login_form': login_form})


def register(request):
    if request.method == 'GET':
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})
    elif request.method == 'POST':
        if request.is_ajax():
            username = request.POST['username']
            user = NewUser.objects.filter(uname=username)
            if user:
                return JsonResponse({'result': '×用户名已被占用'})
            else:
                result = {'result': '√用户名可以使用'}
                return JsonResponse(result)
        else:
            register_form = RegisterForm(request.POST)
            if register_form.is_valid():
                username = register_form.cleaned_data['username']
                email = register_form.cleaned_data['email']
                password = register_form.cleaned_data['password']
                r_password = register_form.cleaned_data['r_password']
                if password != r_password:
                    return render(request, 'register.html', {'error_msg': '两次密码不一致'})
                else:
                    user = NewUser(uname=username, uemail=email, upwd=password)
                    user.save()
                    return redirect('/blog/login/')


def mylogout(request):
    # 清空django_session信息
    request.session.flush()
    # del request.session['uname']
    return redirect('/blog/index/')

def test(request):
    #get_full_path()函数：参数和路径都能获取  /blog/test/?name=zhangsan&age=20
    #path属性：获取不到参数 /blog/test/
    print '----------', request.get_full_path()
    print '==========', request.path
    return render(request, 'login.html')
